from flask import jsonify
from app.api.v1 import bp
from app.models.marine_area import MarineArea
from app.models.industry_score import IndustryScore
from app.models.ecological_indicator import EcologicalIndicator
from sqlalchemy import func
from datetime import datetime, timedelta
from app.extensions import db

@bp.route('/statistics/overview', methods=['GET'])
def get_statistics_overview():
    """
    获取总体统计概览数据
    返回: 所有海域的统计概览，包括平均分、各项指标汇总等
    """
    # 获取基础统计数据
    marine_areas_count = MarineArea.query.count()
    industry_scores_count = IndustryScore.query.count()
    indicators_count = EcologicalIndicator.query.count()
    
    # 获取最近30天的数据更新统计
    thirty_days_ago = datetime.now() - timedelta(days=30)
    recent_scores = IndustryScore.query.filter(
        IndustryScore.created_at >= thirty_days_ago
    ).count()
    recent_indicators = EcologicalIndicator.query.filter(
        EcologicalIndicator.created_at >= thirty_days_ago
    ).count()
    
    return jsonify({
        'total_marine_areas': marine_areas_count,
        'total_industry_scores': industry_scores_count,
        'total_indicators': indicators_count,
        'recent_updates': {
            'scores': recent_scores,
            'indicators': recent_indicators
        }
    })

@bp.route('/statistics/industry-distribution', methods=['GET'])
def get_industry_distribution():
    """
    获取产业分布统计
    返回: 各海域的产业分布情况统计数据
    """
    distribution = db.session.query(
        IndustryScore.industry_type,
        func.avg(IndustryScore.score).label('avg_score'),
        func.count(IndustryScore.id).label('count')
    ).group_by(IndustryScore.industry_type).all()
    
    return jsonify([{
        'industry_type': item.industry_type,
        'average_score': float(item.avg_score),
        'count': item.count
    } for item in distribution]) 